﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace NightskyMimic.Domain
{
    public static class Battle
    {
        //Ações de ataque que não foram bloqueadas, player recebe o dano
        public static int CombatDamage(List<Attack> actions)
        {
            int damage = 0;

            foreach (Attack a in actions)
                damage += a.Target.Power;

            return damage;
        }

        //Dictionary{Attacker, [Blockers]}
        public static Dictionary<Creature, List<Block>> OrganizeBlockers(List<Block> actions)
        {
            Dictionary<Creature, List<Block>> result = new Dictionary<Creature, List<Block>>();

            foreach (Block a in actions)
            {
                if (result.ContainsKey(a.Attacker))
                    result[a.Attacker].Add(a);

                else
                    result.Add(a.Attacker, new List<Block>() { a });
            }

            return result;
        }

        //List[0] -> my blocking dead creatures
        //List[1] -> opponent attacking dead creatures
        public static List<List<Creature>> Combat(List<Attack> attack, List<Block> block)
        {
            attack.ForEach(x => x.Resolved = false);
            List<List<Creature>> result = new List<List<Creature>>() { new List<Creature>(), new List<Creature>() };

            Dictionary<Creature, List<Block>> blocks = OrganizeBlockers(block);

            foreach (Creature a in blocks.Keys)
            {
                List<Block> blockers = blocks[a];
                attack.First(x => x.Target.Id == a.Id).Resolved = true;
                int attackerLife = a.Toughness;

                foreach (Block blocker in blockers)
                {
                    blocker.Resolved = true;
                    attackerLife -= blocker.Target.Power;

                    if (blocker.Target.Toughness - a.Power < 1)
                        result[0].Add(blocker.Target);

                    if (attackerLife < 1)
                    {
                        result[1].Add(a);
                        continue;
                    }
                }
            }
            return result;
        }

    }
}